<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索和添加 -->
          <el-input placeholder="请输入内容" v-model="queryParams.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="editUser(0)">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 数据列表 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
              <el-button
                circle
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="editUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <el-button
                circle
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="deleUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                circle
                size="mini"
                type="warning"
                icon="el-icon-setting"
                @click="editUserRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pagenum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="queryParams.pagesize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
    </el-card>
    <!-- 用户编辑对话框 -->
    <el-dialog
      :title="editUserId?'修改用户':'添加用户'"
      :visible.sync="editDialogVisible"
      @close="editDialogclosed"
      width="30%"
    >
      <!-- 主体表单 -->
      <el-form :model="userInfo" :rules="userInfoRules" ref="userForm" label-width="70px">
        <el-form-item label="用户名" :prop="editUserId==0?'username':''">
          <el-input v-model="userInfo.username" :disabled="editUserId>0"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="editUserId==0">
          <el-input v-model="userInfo.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userInfo.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="userInfo.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 用户角色编辑对话框 -->
    <el-dialog
      title="修改用户角色"
      :visible.sync="showEditRoleDialog"
      @close="editRoleDialogclosed"
      width="30%"
    >
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <p>分配新角色：</p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱规则
    const checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) return cb()
      cb(new Error('请输入合法的邮箱地址！'))
    }
    // 验证手机规则
    const checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) return cb()
      cb(new Error('请输入合法的手机号码！'))
    }
    return {
      // 角色列表
      rolesList: [],
      // 获取用户列表的参数
      queryParams: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      // 用户列表
      userList: [],
      // 用户总数
      total: 0,
      // 是否显示编辑对话框
      editDialogVisible: false,
      // 编辑用户 id
      editUserId: 0,
      // 编辑的用户信息
      userInfo: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 用户信息校验
      userInfoRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名 为 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '密码 为 6 到 15 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 是否显示用户角色对话框
      showEditRoleDialog: false
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryParams
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
    },
    handleSizeChange(newSize) {
      this.queryParams.pagesize = newSize
      this.getUserList()
      // console.log(newSize)
    },
    handleCurrentChange(newPage) {
      this.queryParams.pagenum = newPage
      this.getUserList()
      // console.log(newPage)
    },
    // 监听Switch开关的状态
    async userStateChanged(userinfo) {
      // console.log(userinfo)
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    // 编辑用户
    async editUser(userID) {
      this.editUserId = userID
      if (userID) {
        const { data: res } = await this.$http.get('users/' + userID)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.userInfo = res.data
      } else {
        this.userInfo = {}
      }
      this.editDialogVisible = true
    },
    // 监听用户编辑对话框的关闭
    editDialogclosed() {
      this.$refs.userForm.resetFields()
    },
    // 监听角色编辑对话框的关闭
    editRoleDialogclosed() {
      // this.$refs.roleForm.resetFields()
    },
    // 保存用户
    saveUser() {
      this.$refs.userForm.validate(async (vaild) => {
        if (!vaild) return
        if (this.editUserId > 0) {
          // 修改
          const { data: res } = await this.$http.put(
            'users/' + this.editUserId,
            this.userInfo
          )
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
        } else {
          // 新增
          const { data: res } = await this.$http.post('users', this.userInfo)
          if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
        }
        this.editDialogVisible = false
        this.getUserList()
      })
    },
    // 删除用户
    async deleUser(deleUserId) {
      const toDel = await this.$confirm('确实要删除该用户吗？', '请确认', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (toDel !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete('users/' + deleUserId)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getUserList()
    },
    // 修改用户角色
    async editUserRole(userInfo) {
      this.userInfo = userInfo
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
      console.log(this.rolesList)
      this.showEditRoleDialog = true
    }
  }
}
</script>

<style lang="less" scoped>
</style>
